import React, { FC, useCallback, useEffect, useRef, useState } from "react";
import "./financeScreen.scss";
import Orbit from "./components/orbit/Orbit";
import { getBiz, getNotice } from "@/config/api/financeScreen";
import { Swiper, SwiperSlide } from 'swiper/react';
import { Autoplay } from 'swiper/modules';
import ImgSwiper from "./components/imgSwiper/imgSwiper";

const FinanceScreen: FC = () => {
    const containerRef = useRef<HTMLDivElement>(null);
    const [rightBottomData, setRightBottomData] = useState<any>([]);   //右下板块
    const [leftTopData, setLeftTopData] = useState<any>([]);   //左上数据
    const [rightTopData, setRightTopData] = useState<any>([]);   //右上数据
    const [middleData, setMiddleData] = useState<any>([]);   //中间数据
    const [leftBottomData, setLeftBottomData] = useState<any>([]);   //左下数据
    const displayNum = 3;
    const progressFontColor = ["#FFBA01", "#54B5FF", "#FF6B4A"];
    const progressLineColor = [{
        color1: "#FFBD29",
        color2: "#FC7649",
    }, {
        color1: "#2E29FF",
        color2: "#496AFC",
    }, {
        color1: "#FF5A29",
        color2: "#EC2B27",
    }]

    // 状态管理：当前激活的tab索引
    const [currentTabIndex, setCurrentTabIndex] = useState(0);
    // 状态管理：当前swiper的slide索引
    const [currentSlideIndex, setCurrentSlideIndex] = useState(0);
    // Swiper实例的引用
    const swiperRef = useRef<any>(null);
    // 定时器引用，用于自动切换控制
    const intervalRef = useRef<NodeJS.Timeout | null>(null);
    // 屏保状态：true表示当前处于屏保模式，false表示正常模式
    const [isScreenSaver, setIsScreenSaver] = useState(false);

    // 最后一次用户活动的时间戳，用于计算无活动时长
    const [lastActivity, setLastActivity] = useState(Date.now());

    // 屏保超时时间：5分钟 = 300000毫秒（当前设置为5秒用于测试）
    const SCREENSAVER_TIMEOUT = 3 * 60 * 1000;
    // const SCREENSAVER_TIMEOUT = 1000;

    useEffect(() => {
        const startAutoSwitch = () => {
            intervalRef.current = setInterval(() => {
                const currentTab = rightBottomData.process[currentTabIndex];
                // 当前tab的总slide数量就是数据项数量
                const totalSlides = currentTab.project.length;

                if (currentSlideIndex < totalSlides - displayNum) {
                    // 当前tab还有更多slides，继续播放下一个slide
                    setCurrentSlideIndex(prev => prev + 1);
                    // 安全检查：确保swiper实例存在且slideNext方法可用
                    if (swiperRef.current && swiperRef.current.slideNext) {
                        swiperRef.current.slideNext();
                    }
                } else {
                    // 当前tab的slides已经播放完，切换到下一个tab
                    const nextTabIndex = (currentTabIndex + 1) % rightBottomData.process.length;
                    setCurrentTabIndex(nextTabIndex);
                    setCurrentSlideIndex(0);
                }
            }, 6000); // 6秒间隔
        };

        // 启动自动切换
        startAutoSwitch();

        // 清理函数：组件卸载或依赖变化时清除定时器
        return () => {
            if (intervalRef.current) {
                clearInterval(intervalRef.current);
            }
        };
    }, [currentTabIndex, currentSlideIndex, rightBottomData]);

    /**
     * 当tab切换时，重置swiper到第一张slide
     * 确保每次切换tab时都从第一个slide开始显示
     */
    useEffect(() => {
        // 安全检查：确保swiper实例存在且slideTo方法可用
        if (swiperRef.current && swiperRef.current.slideTo) {
            swiperRef.current.slideTo(0);
        }
    }, [currentTabIndex]);

    const handleResize = () => {
        if (!containerRef.current) return;

        const designWidth = 1920;
        const designHeight = 1080;
        const currentWidth = window.innerWidth;
        const currentHeight = window.innerHeight;

        // 计算宽高比例
        const widthRatio = currentWidth / designWidth;
        const heightRatio = currentHeight / designHeight;

        // 应用变换
        containerRef.current.style.transform = `scale(${parseFloat(widthRatio.toFixed(5))},${parseFloat(heightRatio.toFixed(5))})`;
        containerRef.current.style.transformOrigin = 'center center';
    };

    // 为函数添加返回类型 any
    const replaceZerosWithDash = (data: any): any => {
        // 如果是数组，递归处理每个元素
        if (Array.isArray(data)) {
            // 为 map 回调函数添加返回类型 any
            return data.map((item: any): any => replaceZerosWithDash(item));
        }

        // 如果是对象，递归处理每个属性
        if (data !== null && typeof data === 'object') {
            // 定义 result 类型，支持字符串索引
            const result: { [key: string]: any } = {};
            for (const key in data) {
                if (data.hasOwnProperty(key)) {
                    result[key] = replaceZerosWithDash(data[key]);
                }
            }
            return result;
        }

        // 如果是字符串"0"或数字0，替换为"-"
        if (data === "0" || data === 0) {
            return "-";
        }

        // 其他情况直接返回原值
        return data;
    };

    const getDataList = () => {
        getBiz().then((res) => {
            const newArr = replaceZerosWithDash(res)
            const middle = newArr.find((item: any) => item.moduleId === 1);
            const leftTop = newArr.find((item: any) => item.moduleId === 2);
            const leftBottom = newArr.find((item: any) => item.moduleId === 3);
            const rightTop = newArr.find((item: any) => item.moduleId === 4);
            setMiddleData(middle);
            setLeftTopData(leftTop);
            setLeftBottomData(leftBottom);
            setRightTopData(rightTop);
        }).catch(err => {
            console.log(err);
        });
    }

    const getRightBottomData = () => {
        getNotice().then((res) => {
            const newArr = replaceZerosWithDash(res);
            setRightBottomData(newArr);
        }).catch(err => {
            console.log(err);
        });
    }

    useEffect(() => {
        getDataList();
        getRightBottomData();
        handleResize();
        window.addEventListener('resize', handleResize);
        return () => window.removeEventListener('resize', handleResize);
    }, []);  // eslint-disable-line

    // 处理字符串换行的函数
    const handleTextWrap = (text: string | undefined) => {
        if (!text) return '';
        // 修改：长度大于6时按奇偶性分配换行
        if (text.length >= 6) {
            const splitIndex = Math.floor(text.length / 2);
            return `${text.slice(0, splitIndex)}<br />${text.slice(splitIndex)}`;
        }
        return text;
    };

    // 计算总数
    const getTotal = (...values: any[]): number => {
        const parseNumber = (value: any): number => {
            if (value === '-') return 0;
            const num = Number(value);
            return isNaN(num) ? 0 : num;
        };

        const result = values.reduce((sum, value) => sum + parseNumber(value), 0);
        // 解决浮点数精度问题，保留2位小数
        return Math.round(result * 100) / 100;
    };
    const formatNumberWithCommas = (num: any) => {
        if (num === "-") return "-";
        else return new Intl.NumberFormat('en-US').format(num);
    }
    const renderSlides = () => {
        const currentTab = rightBottomData.process[currentTabIndex];

        return currentTab.project.map((item: any, index: number) => (
            <SwiperSlide key={index}>
                <div className="slide-content">
                    {/* 数据项名称 */}
                    <div className="item-name">{item.projectTypeName}</div>
                    <div className="item-title">预算收入<br /><span>￥{formatNumberWithCommas(item.projectFieldValue)}</span></div>
                    <div className="item-title">财务入账<br /><span>￥{formatNumberWithCommas(item.projectFieldValueFinished)}</span></div>
                    <div className="progress">
                        <div className="progress-bar" >
                            <span className="title1">执行进度</span>
                            <span className="num" style={{ color: progressFontColor[index % progressFontColor.length] }}>{item.percent}</span>
                        </div>
                        <div className="progress-bg">
                            <div className="progress-line"
                                style={{
                                    width: `${parseInt(item.percent) >= 100 ? 100 : parseInt(item.percent)}%`,
                                    background: `linear-gradient(27deg, ${progressLineColor[index % progressLineColor.length].color1} 0%, ${progressLineColor[index % progressLineColor.length].color2} 100%)`
                                }}
                            ></div>
                        </div>
                    </div>
                </div>
            </SwiperSlide>
        ));
    };

    /**
  * 重置用户活动时间的回调函数
  * 功能：
  * 1. 更新最后活动时间为当前时间
  * 2. 如果当前处于屏保状态，则退出屏保模式
  * 使用useCallback优化性能，避免不必要的重新渲染
  */
    const resetActivity = useCallback(() => {
        setLastActivity(Date.now());
        if (isScreenSaver) {
            setIsScreenSaver(false);
        }
    }, [isScreenSaver]);
    useEffect(() => {
        // 定义需要监听的用户活动事件类型
        const events = [
            'mousedown',   // 鼠标按下事件
            'mousemove',   // 鼠标移动事件
            'keypress',    // 键盘按键事件
            'scroll',      // 页面滚动事件
            'touchstart',  // 触摸开始事件（支持移动设备）
            'click'        // 鼠标点击事件
        ];

        // 为每个事件类型添加全局事件监听器
        // 使用捕获阶段（true）确保能够捕获到所有事件
        events.forEach(event => {
            document.addEventListener(event, resetActivity, true);
        });

        // 组件卸载时清理所有事件监听器，防止内存泄漏
        return () => {
            events.forEach(event => {
                document.removeEventListener(event, resetActivity, true);
            });
        };
    }, [resetActivity]);
    /**
     * 定时检查是否需要进入屏保状态的副作用钩子
     * 逻辑：
     * 1. 每秒检查一次当前时间与最后活动时间的差值
     * 2. 如果超过设定的超时时间且当前不在屏保状态，则进入屏保
     * 3. 使用定时器实现周期性检查
     */
    useEffect(() => {
        // 检查屏保状态的函数
        const checkScreenSaver = () => {
            const now = Date.now();
            // 计算无活动时长，如果超过超时时间且当前不在屏保状态，则进入屏保
            if (now - lastActivity >= SCREENSAVER_TIMEOUT && !isScreenSaver) {
                setIsScreenSaver(true);
            }
        };

        // 设置定时器，每秒检查一次屏保状态
        const interval = setInterval(checkScreenSaver, 1000);

        // 清理定时器，防止内存泄漏
        return () => clearInterval(interval);
    }, [lastActivity, isScreenSaver, SCREENSAVER_TIMEOUT]);

    return (
        <>
            <div className="screen-container">
                <div className="finance-screen" ref={containerRef}>
                    {
                        isScreenSaver ? <ImgSwiper ImgSwiperData={rightBottomData.notice} /> :
                            <div className="content-wrapper">
                                <div className="main-bg-1">
                                    <div className="shine"></div>
                                </div>
                                <div className="content-box">
                                    <div className="content-left">
                                        {
                                            leftTopData && Object.keys(leftTopData).length > 0 && <div className="left-top">
                                                <div className="title">{leftTopData.moduleName}</div>
                                                {/* <div className="total-money">(总营收金额：{leftTopData.totalRevenue}万元)</div> */}
                                                <div className="confirm-project">
                                                    <div className="projrct-title">拓展项目</div>
                                                    <div className="state">
                                                        <div>数量：{leftTopData.projectNum}个</div>
                                                        <div>合同金额：{leftTopData.totalAmount}万元</div>
                                                    </div>
                                                </div>
                                                <div className="swiper-left-top">
                                                    <Swiper
                                                        direction="vertical" // 设置为纵向滚动
                                                        slidesPerView={3} // 同时显示3个滑块
                                                        spaceBetween={10} // 滑块间距20px
                                                        autoplay={{
                                                            delay: 2000, // 自动播放间隔2秒
                                                            disableOnInteraction: false, // 用户交互后不停止自动播放
                                                        }}
                                                        loop={leftTopData.project.length > 3} // 动态设置是否循环播放
                                                        modules={[Autoplay]} // 启用自动播放模块
                                                        className="swiper-wrapper"
                                                    >
                                                        {/* 遍历滑块数据并渲染 */}
                                                        {leftTopData?.project.length > 0 && leftTopData.project.map((item: any, index: number) => (
                                                            <SwiperSlide key={index}>
                                                                <div className="slide-item" >
                                                                    <span className="sub-title">{item.projectTypeName}</span>
                                                                    <div className="item">
                                                                        <div className="state">
                                                                            <div className="state-title">
                                                                                <div className="state-small-title">
                                                                                    <span>{item?.attribute[0].projectFieldName}</span>
                                                                                    <span>（{item?.attribute[0].projectFieldUnit}）</span>
                                                                                </div>
                                                                                <div className="state-money">{item?.attribute[0].projectFieldValue}</div>
                                                                            </div>
                                                                            <div className="state-title">
                                                                                <div className="state-small-title">
                                                                                    <span>{item?.attribute[2].projectFieldName}</span>
                                                                                    <span>（{item?.attribute[2].projectFieldUnit}）</span>
                                                                                </div>
                                                                                <div className="state-money">{item?.attribute[2].projectFieldValue}</div>
                                                                            </div>
                                                                            <span
                                                                                className="state-plan"
                                                                                dangerouslySetInnerHTML={{ __html: handleTextWrap(item?.attribute[1].projectFieldValue) }}
                                                                            />
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            </SwiperSlide>
                                                        ))}
                                                    </Swiper>
                                                </div>
                                            </div>
                                        }
                                        {
                                            leftBottomData && Object.keys(leftBottomData).length > 0 && <div className="left-bottom">
                                                <div className="swiper-left-bottom-container">
                                                    <Swiper
                                                        direction="horizontal" // 设置为横向滚动
                                                        slidesPerView={3} // 同时显示3个滑块
                                                        spaceBetween={10} // 滑块间距10px
                                                        autoplay={{
                                                            delay: 2000, // 自动播放间隔2秒
                                                            disableOnInteraction: false, // 用户交互后不停止自动播放
                                                        }}
                                                        loop={leftBottomData.project.length > 3} // 只有滑块数量大于3个时才开启循环播放
                                                        modules={[Autoplay]} // 启用自动播放模块
                                                        className="swiper-wrapper"
                                                    >
                                                        {/* 遍历滑块数据并渲染 */}
                                                        {leftBottomData?.project.length > 0 && leftBottomData.project.map((item: any, index: number) => (
                                                            <SwiperSlide key={index}>
                                                                <div className={"slide-item"}>
                                                                    <div className="item">
                                                                        <div className={item.projectTypeName.length > 5 ? "title-fontsize" : "title"}>{item.projectTypeName}</div>
                                                                        {
                                                                            item?.attribute.length > 0 && item.attribute.map((itemAtt: any, indexAtt: number) => (
                                                                                <div className="state" key={indexAtt}>
                                                                                    <div className="state-title">{itemAtt.projectFieldName}<span>{itemAtt.projectFieldUnit !== null && itemAtt.projectFieldUnit !== undefined ? `（${itemAtt.projectFieldUnit}）` : ""}</span>：</div>
                                                                                    <span className="state-num">{itemAtt.projectFieldValue}</span>
                                                                                    <div className="white-line"></div>
                                                                                </div>
                                                                            ))
                                                                        }
                                                                    </div>
                                                                </div>
                                                            </SwiperSlide>
                                                        ))}
                                                    </Swiper>
                                                </div>
                                            </div>
                                        }
                                    </div>
                                    {
                                        middleData && Object.keys(middleData).length > 0 && <div className="content-middle">
                                            {/* 市场开拓板块预算收入 */}
                                            <div className="left-top-round">
                                                {/* 三角形 */}
                                                <div className="triangle-left-middle"></div>
                                                {/* 圆形 */}
                                                <div className="small-round">
                                                    <div className="title">市场开拓<br />预算收入</div>
                                                    <div className="money">{getTotal(leftTopData.totalRevenue, leftTopData.totalAmount)}</div>
                                                    <div className="unit">万元</div>
                                                </div>
                                                {/* 三角形 */}
                                                <div className="triangle-right-middle"></div>
                                            </div>
                                            {/* 总预算收入 */}
                                            <div className="total-num">
                                                <div className="title">总预算收入</div>
                                                <div className="money">{getTotal(leftTopData.totalRevenue, leftTopData.totalAmount, middleData.totalRevenue, rightTopData.totalRevenue, rightTopData.totalAmount)}</div>
                                                <div className="unit">万元</div>
                                            </div>
                                            <div className="main-bg-2"></div>

                                            {/* 基础业务 */}
                                            <div className="middle-top-round">
                                                {/* 三角形 */}
                                                <div className="triangle-top-middle"></div>
                                                <div className="small-round">
                                                    <div className="title">基础业务<br />预算收入</div>
                                                    <div className="money">{middleData.totalRevenue}</div>
                                                    <div className="unit">万元</div>
                                                </div>
                                            </div>

                                            {/* 科技研发预算收入 */}
                                            <div className="right-top-round">
                                                <div className="triangle-left-middle"></div>
                                                {/* 圆形 */}
                                                <div className="small-round">
                                                    <div className="title">科技研发<br />预算收入 </div>
                                                    <div className="money">{getTotal(rightTopData.totalRevenue, rightTopData.totalAmount)}</div>


                                                    <div className="unit">万元</div>
                                                </div>
                                                {/* 三角形 */}
                                                <div className="triangle-right-middle"></div>
                                            </div>

                                            <div className="middle-bottom">
                                                <Orbit tabItems={middleData.project}></Orbit>
                                            </div>
                                        </div>
                                    }
                                    <div className="content-right">
                                        {
                                            rightTopData && Object.keys(rightTopData).length > 0 && <div className="right-top">
                                                <div className="right-title">
                                                    <div className="title">{rightTopData.moduleName}</div>
                                                    {/* <span className="total-money">(总营收金额：{rightTopData.totalRevenue}万元)</span> */}
                                                </div>
                                                <div className="confirm-project">
                                                    <div className="title">拓展项目</div>
                                                    <div className="state">
                                                        <div>数量：{rightTopData.projectNum}个</div>
                                                        <div>合同金额：{rightTopData.totalAmount}万元</div>
                                                    </div>
                                                </div>
                                                <div className="swiper-right-top">
                                                    <Swiper
                                                        direction="vertical" // 设置为纵向滚动
                                                        slidesPerView={displayNum} // 同时显示3个滑块
                                                        spaceBetween={10} // 滑块间距20px
                                                        autoplay={{
                                                            delay: 2000, // 自动播放间隔2秒
                                                            disableOnInteraction: false, // 用户交互后不停止自动播放
                                                        }}
                                                        loop={rightTopData.project.length > 3} // 动态设置是否循环播放
                                                        modules={[Autoplay]} // 启用自动播放模块
                                                        className="swiper-wrapper"
                                                    >
                                                        {/* 遍历滑块数据并渲染 */}
                                                        {rightTopData?.project.length > 0 && rightTopData.project.map((item: any, index: number) => (
                                                            <SwiperSlide key={index}>
                                                                <div className="slide-item" >
                                                                    <span className="sub-title">{item.projectTypeName}</span>
                                                                    <div className="item">
                                                                        <div className="state">
                                                                            <div className="state-title">
                                                                                <div className="state-small-title">
                                                                                    <span>{item?.attribute[0].projectFieldName}</span>
                                                                                    <span>（{item?.attribute[0].projectFieldUnit}）</span>
                                                                                </div>
                                                                                <div className="state-money">{item?.attribute[0].projectFieldValue}</div>
                                                                            </div>
                                                                            <div className="state-title">
                                                                                <div className="state-small-title">
                                                                                    <span>{item?.attribute[2].projectFieldName}</span>
                                                                                    <span>（{item?.attribute[2].projectFieldUnit}）</span>
                                                                                </div>
                                                                                <div className="state-money">{item?.attribute[2].projectFieldValue}</div>
                                                                            </div>
                                                                            <span className="state-plan">{item?.attribute[1].projectFieldValue}</span>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            </SwiperSlide>
                                                        ))}
                                                    </Swiper>
                                                </div>
                                            </div>
                                        }
                                        {
                                            rightBottomData?.process?.length > 0 && <div className="right-bottom">
                                                <div className="right-bottom-title">实际营收进度</div>
                                                {/* Tab导航栏 */}
                                                <div className="tab-nav">
                                                    {rightBottomData.process?.length > 0 && rightBottomData.process.map((tab: any, index: number) => (
                                                        <div
                                                            key={index}
                                                            className={`tab-item ${currentTabIndex === index ? 'active' : ''}`}
                                                        >
                                                            {tab.moduleName}
                                                        </div>
                                                    ))}
                                                </div>
                                                <div className="swiper-container">
                                                    <div className="swiper-content">
                                                        <Swiper
                                                            className="swiper-wrapper"
                                                            direction="horizontal"
                                                            modules={[Autoplay]} // 启用自动播放模块
                                                            slidesPerView={3} // 每次显示3个slide
                                                            spaceBetween={12} // slide之间的间距
                                                            loop={false} // 不启用循环模式
                                                            allowTouchMove={false} // 禁用手势滑动
                                                            onSwiper={(swiper: any) => {
                                                                // 获取swiper实例并保存到ref中
                                                                swiperRef.current = swiper;
                                                            }}
                                                            onSlideChange={(swiper: any) => {
                                                                // slide变化时更新当前slide索引
                                                                setCurrentSlideIndex(swiper.activeIndex);
                                                            }}
                                                        >
                                                            {/* 渲染所有slides */}
                                                            {renderSlides()}
                                                        </Swiper>
                                                        <div className="swiper-state">
                                                            <div className="item" style={{ marginRight: 12 }}>预算收入合计<br /><span>￥{formatNumberWithCommas(rightBottomData.totalProjectFieldValue)}</span></div>
                                                            <div className="item" style={{ marginRight: 12 }}>财务入账合计<br /><span>￥{formatNumberWithCommas(rightBottomData.totalProjectFieldValueFinished)}</span></div>
                                                            <div className="item">执行进度<br /><span>{rightBottomData.totalPercent}</span></div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        }
                                    </div>
                                    <div className="click-lock-screen" onClick={() => setIsScreenSaver(true)}>一键锁屏</div>
                                </div>
                            </div>
                    }

                </div>
            </div>

        </>
    );
};

export default FinanceScreen;